/**
 * 数据集区域配置、数据集规则配置、数据集数据展示相关
 */
import {
  addDataset, // 保存数据集配置:
  editDataset, // 修改数据集配置:
  queryDatasetData, // 通过信息查询:
  editDatasetData, //  数据集数据批量修改:
  queryDatasetDataList, //  数据集数据批量修改:
  deleteDatasetData, //  数据集数据批量修改:
  addReportVerify, // 数据检核规则表-添加
  deleteReportVerify, // 数据检核规则表-通过id删除
  editReportVerify, // 数据检核规则表-编辑
  getReportVerify, // 数据检核规则表-分页列表查询
  findAllFrom,
  findAllColumns,
} from '@/api/websheet.js'
import {
  dataSysColumns,
  sjjRuleColumns,
} from '../export'

export const SjjMixin = {
  data() {
    return {
      dataSysColumns,
      sjjRuleColumns,
      dataSysRange: {}, //数据集配置坐标
      sjjpzItem: {}, //数据集配置详情
      dataSysStatus: false, //数据集配置区域是否重合
      formData: {}, //数据集配置
      validatorRules: {
        tableName: [{ required: true, message: '请选择查询表!' }],
        columns: [{ required: true, message: '请选择查询字段!' }],
        sqlval: [{ required: true, message: '请填写SQL语句!' }],
        xzmc: [{ required: true, message: '请填写区域名称!' }],
        xzqy: [{ required: true, message: '请框选左侧区域!' }],
        hbcolumns: [{ required: false, message: '请框选合并字段!' }],
        noRenderCol: [{ required: false, message: '请框选不渲染字段!' }],
      },
      sjjpzList: [], //数据集配置列表
      allDataList: [], //数据集数据
      influenceFunc: {}, //所有模板公式按单元格为key的关联关系
      sjjRule: {}, //数据集规则配置
      validatorFormRules: {
        rangeId: [{ required: true, message: '请选择区域!' }],
        syfw: [{ required: true, message: '请选择适用范围!' }],
        yzzd: [{ required: true, message: '请选择验证字段!' }],
        gltj: [{ required: true, message: '请填写筛选条件!' }],
        yzgs: [{ required: true, message: '请填写验证公式!' }],
        tssm: [{ required: true, message: '请填写提示说明!' }],
        bz: [{ required: false, message: '请填写备注!' }],
        bjys: [{ required: false, message: '请填写背景颜色!' }],
      },
      sjjRuleList: [], //数据集规则列表
      sjjRuleItem: {}, //数据集规则详情
      sjjRuleStatus: false, //数据集规则修改loding状态
      allFroms: [],//获取所有表单
      allColumns: {},//获取所有表单字段
      sjjActive: 'dataSys',//数据集tab
      formDataStatus: false,
      sjlxList: [],
    }
  },
  created() {

  },
  methods: {
    pushsjlxList() {
      const list = this.sjlxList;
      const item = {
        key: this.formData.sjtype,
        value: this.formData.zdtype
      }
      this.formData.sjtype = ''
      this.formData.zdtype = []
      list.push(item)
      this.sjlxList = list
    },
    delsjlxList(key) {
      const list = this.sjlxList.filter(item => item.key !== key);
      this.sjlxList = list
    },
    //获取所有表单
    queryAllFrom() {
      findAllFrom().then((res) => {
        if (res.code === 200) {
          this.allFroms = res.result || []
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
    // 数据集规则配置选择区域
    getAllColumns(value) {
      this.queryAllColumns(this.sjjpzList.filter(item => item.id === value)[0].sqlval.split('FROM')[1].trim(), true)
    },
    //获取所有表单字段
    queryAllColumns(tableName, status) {
      if (!status) {
        this.formData = {
          ...this.formData, columns: [], hbcolumns: [],
          noRenderCol: [],
        }
      }
      this.formDataStatus = true
      if (!(this.allColumns && this.allColumns[tableName])) {
        findAllColumns({ tableName }).then((res) => {
          if (res.code === 200) {
            this.allColumns = { ...this.allColumns, [tableName]: res.result || [] }
          } else {
            this.$message.warning('服务器出错!')
          }
          this.formDataStatus = false
        })
      }
    },
    // 数据集规则保存
    saveSjjRule(type) {
      this.sjjRuleStatus = true
      this.$refs[`${type}Rule`].validate((valid) => {
        if (valid) {
          if (this[`${type}RuleItem`] && this[`${type}RuleItem`].id) {
            const data = type === 'target' ? { syfw: '0', yzzd: this[`${type}RuleItem`].gltj, jclx: '1' } : { jclx: '0' }
            editReportVerify({ ...this[`${type}RuleItem`], ...this[`${type}Rule`], ...data }).then((res) => {
              if (res.code === 200) {
                this.$message.success('保存成功!')
                this.queryReportVerify(this.exportJson)
                this.clearSjjRuleEdit(type)
              } else {
                this.$message.warning('服务器出错!')
              }
              this.sjjRuleStatus = false
            })
          } else {
            addReportVerify({
              bbdm: this.exportJson.bbdm,
              mbdm: this.exportJson.mbbm,
              ...this[`${type}Rule`],
            }).then((res) => {
              if (res.code === 200) {
                this.$message.success('添加成功!')
                this.clearSjjRuleEdit(type)
                this.queryReportVerify(this.exportJson)
              } else {
                this.$message.warning('服务器出错!')
              }
              this.sjjRuleStatus = false
            })
          }
        } else {
          this.sjjRuleStatus = false
          return false
        }
      })
    },
    // 数据集规则配置取消修改
    clearSjjRuleEdit(type) {
      this[`${type}RuleItem`] = {}
      this[`${type}Rule`] = {}
      this.$refs[`${type}Rule`].resetFields()
    },
    //数据集规则配置开始修改
    editSjjRule(record, type) {
      const data = JSON.parse(JSON.stringify(record))
      this[`${type}RuleItem`] = data
      this[`${type}Rule`] = data
      if (type === 'sjj') {
        console.log('%c [ this.sjjpzList ]-154', 'font-size:13px; background:pink; color:#bf2c9f;', this.sjjpzList, record)
        this.queryAllColumns(this.sjjpzList.filter(item => item.id === record.rangeId)[0].sqlval.split('FROM')[1].trim(), true)

      }
    },
    // 数据集规则删除
    delReportVerify(record) {
      this.sjjRuleStatus = true
      deleteReportVerify({ id: record.id }).then((res) => {
        if (res.code === 200) {
          this.$message.success('删除成功!')
          this.queryReportVerify(record)
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
    // 指标、数据集规则列表
    queryReportVerify(record) {
      this.sjjRuleStatus = true
      getReportVerify({
        bbdm: (record && record.bbdm) || this.exportJson.bbdm,
        mbdm: (record && record.mbbm) || this.exportJson.mbbm,
      }).then((res) => {
        if (res.code === 200) {
          let list = res.result.records || []
          this.sjjRuleList = list
          this.sjjRuleStatus = false
          if (this.type === 'render') {
            // 先获取规则再调用指标渲染数据
            this.queryReportDataList(record)
          }
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
    // 批量修改数据集数据
    setDatasetData(record) {
      editDatasetData(record).then((res) => {
        if (res.code === 200) {
          this.$message.success('修改成功!')
          // this.getAllDataList(this.exportJson, {},false)
        } else {
          this.$message.warning('服务器出错!')
        }
        this.sjjIEditStatus = true
      })
    },
    // 获取数据集所有展示数据
    getAllDataList(record, options, status) {
      this.queryReportParam()
      this.ssjLoading = true
      console.log((this.parameter.bbdmS)||(record && record.bbdm) || this.exportJson.bbdm);      console.log(this.parameter);
      queryDatasetData({
        bbdm: (record && record.bbdm) || this.exportJson.bbdm,
        bbdmn: this.parameter.bbdmS,
        mbdm: (record && record.mbbm) || this.exportJson.mbbm,
        bspc: this.parameter.bbpc,
        ssjg: this.parameter.ssjg,
        frdm: this.parameter.frdm,
      }).then((res) => {
        if (res.code === 200) {
          // 合并策略
          let list = res.result ? JSON.parse(res.result) : []
          this.allDataList = list
          if (this.sjjpzList && this.sjjpzList <= 0 && status) {
            this.ssjLoading = false
            this.drawExcel(options, record)
            return
          }
          let mcList = []
          if (list.length <= 0) {
            console.log('%c [ list.length ]-222', 'font-size:13px; background:pink; color:#bf2c9f;', list.length)
            this.ssjLoading = false
            if (status) {
              this.drawExcel(options, record)
            }
          } else {
            list.map((item, index) => {
              if (item.list.length <= 0 && status) {
                this.drawExcel(options, record)
                return
              }
              // 获取当前区域数据集配置
              const qyItem = this.sjjpzList[index]
              let range = JSON.parse(qyItem.xzqy)
              // 不渲染的字段
              let noRenderCol = qyItem && qyItem.noRenderCol || ''
              // 使用sql语句顺序渲染
              const sqlvalList = qyItem && qyItem.sqlval && qyItem.sqlval.replace('SELECT', '').trim().split('FROM')[0].trim().split(',') || []
              // 计算除去不渲染字段后的列长度
              const length = sqlvalList.filter(el => noRenderCol.indexOf(el.toUpperCase()) === -1).length
              // 设置渲染区域边框加黑
              record.sheets[0].config.borderInfo.push(
                {
                  "rangeType": "range",
                  "borderType": "border-all",
                  "color": "#000",
                  "style": "1",
                  "range": [
                    {
                      "row": [range.row[0], range.row[0] + item.list.length - 1],
                      "column": [range.column[0], range.column[0] + length - 1]
                    }
                  ]
                }
              )
              // 计算合并的单元格坐标
              mcList =
                qyItem && qyItem.hbcolumns
                  ? this.loopMcList(item.list, JSON.parse(JSON.stringify(range)), qyItem)
                  : []
              for (const key in mcList) {
                mcList[key].map((el) => {
                  record.sheets[0].config.merge[`${el.mc.r}_${el.mc.c}`] = el.mc
                })
              }
            })
            // 每次渲染要流出时间不然会报错
            if (status) {
              this.drawExcel(options, record)
            }
            setTimeout(() => {
              // const rangeList = this.sjjpzList.map((item) => {
              //   return JSON.parse(item.xzqy)
              // })
              // this.drawRange(rangeList)
              list.map((item, index) => {
                let celldata = []
                if (item.list.length > 0) {
                  const data = { date: item.date, gjdm: item.gjdm, id: item.id }
                  let range = JSON.parse(this.sjjpzList[index].xzqy)
                  let rule = this.sjjRuleFilter.filter((el) => el.rangeId === item.rangeId) || []
                  // item.list.map((el, i) => {
                  //   const row = range.row[0] + i
                  //   let newRange = JSON.parse(JSON.stringify(range))
                  //   newRange.row = [row, row]
                  //   // setTimeout(() => {
                  //   //   this.loopSetValue(mcList, el, { ...newRange, ...data }, rule, celldata, this.sjjpzList[index])
                  //   // }, 0)
                  //   this.loopSetValue(mcList, el, { ...newRange, ...data }, rule, celldata, this.sjjpzList[index])
                  // })
                  // 此处是为了更快速能看到页面，不需要长时间等待loading
                  this.loopsjj(0, item.list, mcList, range, rule, data, celldata, this.sjjpzList[index])
                } else {
                  this.ssjLoading = false
                }
                if (index == list.length - 1 && item.list.length < 0) {
                  this.ssjLoading = false
                }
                setTimeout(() => {
                  if (celldata.length > 0) {
                    celldata.map((item, i) => {
                      luckysheet.setCellFormat(item.row, item.column, 'ps', item.ps)
                    })
                  }
                }, item.list.length * 30 + 100)
              })
            }, 500)
          }
        } else {
          if (status) {
            this.drawExcel(options, record)
          }
          this.ssjLoading = false
          this.$message.warning('服务器出错!')
        }
        if (this.type === 'render') {
          this.queryReportParam()
        }
      })
    },
    // 数据循环渲染到Excel
    loopsjj(num, list, mcList, range, rule, data, celldata, qyItem) {
      const row = range.row[0] + num
      let newRange = JSON.parse(JSON.stringify(range))
      newRange.row = [row, row]
      this.loopSetValue(mcList, list[num], { ...newRange, ...data }, rule, celldata, qyItem)
      if (num + 1 < list.length) {
        setTimeout(() => {
          this.loopsjj(num + 1, list, mcList, range, rule, data, celldata, qyItem)
        }, 0)
      } else {
        if (this.type === 'render') {
          this.ssjLoading = false
          luckysheet.refreshFormula()
        }
        if (celldata.length > 0) {
          celldata.map((item, i) => {
            luckysheet.setCellFormat(item.row, item.column, 'ps', item.ps)
          })
        }
      }
    },
    //合并单元格
    loopMcList(list, range, qyItem) {
      let merge = qyItem && qyItem.hbcolumns
      let forItem = list[0]
      let mcList = {}
      let columnNum = 0 //列坐标
      let mergeList = merge ? (merge.indexOf(',') > -1 ? merge.split(',') : [merge]) : []
      const sqlvalList = qyItem.sqlval.replace('SELECT', '').trim().split('FROM')[0].trim().split(',')
      sqlvalList.map((key, columnNum) => {
        key = key.trim().toUpperCase()
        if (key !== 'ID' && mergeList.some((item) => item.toUpperCase() === key)) {
          let i = 0 //行坐标
          let keyList = [forItem[key].value] //当前要比较的值
          while (keyList.length > 0) {
            // 当前是否最后一行
            if (i < list.length) {
              let mcStatus = true
              let x = i //当前行坐标用于下一个比较
              while (mcStatus) {
                // 要比较的不是最后一行
                if (x + 1 < list.length) {
                  // 下一行值相同时
                  if (list[x + 1][key].value === keyList[keyList.length - 1]) {
                    x++
                  } else {
                    // 下一行值不同时已经跨行
                    if (x > i) {
                      const r = range.row[0] + i
                      const c = range.column[0] + columnNum
                      //合并单元格必备属性
                      const mc = {
                        r, //主单元格的行号
                        c, //主单元格的列号
                        rs: x - i + 1, //合并单元格占的行数
                        cs: 1, //合并单元格占的列数
                      }
                      // 存入合并信息
                      if (mcList[key]) {
                        mcList[key].push({ mc, value: forItem[key].value })
                      } else {
                        mcList[key] = [{ mc, value: forItem[key].value }]
                      }
                    }
                    // 下一行值不同时存入keyList下次比较的值，结束当前循环mcStatus，记录下行坐标i
                    mcStatus = false
                    i = x + 1
                    keyList.push(list[x + 1][key].value)
                  }
                } else {
                  // 比较最后一行时已经跨行
                  if (x > i) {
                    const r = range.row[0] + i
                    const c = range.column[0] + columnNum
                    //合并单元格必备属性
                    const mc = {
                      r, //主单元格的行号
                      c, //主单元格的列号
                      rs: x - i + 1, //合并单元格占的行数
                      cs: 1, //合并单元格占的列数
                    }
                    // 存入合并信息
                    if (mcList[key]) {
                      mcList[key].push({ mc, value: forItem[key].value })
                    } else {
                      mcList[key] = [{ mc, value: forItem[key].value }]
                    }
                  }
                  // 结束循环
                  mcStatus = false
                  keyList = []
                }
              }
            } else {
              // 最后一行结束循环
              keyList = []
            }
          }
        }
      })
      return mcList || null
    },
    // 渲染数据
    loopSetValue(mcList, list, record, rule, celldata, qyItem) {
      if (!Array.isArray(list)) {
        // let i = 0
        // 不渲染的字段
        let noRenderCol = qyItem.noRenderCol
          ? qyItem.noRenderCol.indexOf(',')
            ? qyItem.noRenderCol.split(',')
            : [qyItem.noRenderCol]
          : []
        // 使用sql语句顺序渲染
        const sqlvalList = qyItem.sqlval.replace('SELECT', '').trim().split('FROM')[0].trim().split(',')
        sqlvalList.map((key, i) => {
          key = key.trim().toUpperCase()
          if (key === 'ID') {
            return
          }
          const datasetData = { datasetData: { key: key, obj: list[key], id: list.ID } }
          const row = record.row[0]
          const column = record.column[0] + i
          // datasetData.row = [row, row]
          // datasetData.column = [column, column]
          // dataList.push()
          // setTimeout(() => {
          //   luckysheet.setCellFormat(row, column, 'datasetData', datasetData)
          // }, 0);
          luckysheet.setCellFormat(row, column, 'datasetData', datasetData)
          i++
          let ps = {} //批注
          let ruleItem = rule.filter((item) => item.yzzd.toUpperCase() === key)
          let gltj = {} //过滤条件
          if (ruleItem.length > 0) {
            //过滤条件字符串解析重组
            if (ruleItem[0].gltj) {
              let gltjList =
                ruleItem[0].gltj.indexOf(' and ') > -1 ? ruleItem[0].gltj.split(' and ') : [ruleItem[0].gltj]
              gltjList.map((item) => {
                if (
                  gltj &&
                  gltj[item.split('=')[0].toUpperCase()] &&
                  gltj[item.split('=')[0].toUpperCase()].length > 0
                ) {
                  gltj[item.split('=')[0].toUpperCase()].push(item.split('=')[1].replace(/\'/g, ''))
                } else {
                  gltj[item.split('=')[0].toUpperCase()] = [item.split('=')[1].replace(/\'/g, '')]
                }
              })
            }
            // 是否符合条件true:符合，false:不符合
            let status = true
            if (gltj) {
              for (const objKey in gltj) {
                if (!gltj[objKey].some((item) => item === (list[objKey] && list[objKey].value))) {
                  status = false
                }
              }
            }
            if (status) {
              // 整列批注
              if (ruleItem[0].syfw === '1') {
                if (!(celldata.length > 0 && celldata.some((item) => item.key === key))) {
                  celldata.push({
                    key,
                    row: record.row[0] - 1,
                    column: column,
                    ps: {
                      //批注
                      left: null, //批注框左边距
                      top: null, //批注框上边距
                      width: null, //批注框宽度
                      height: null, //批注框高度
                      value: ruleItem[0].tssm, //批准内容
                      isshow: false, //批注框为显示状态
                    },
                  })
                }
              } else {
                if (
                  mcList &&
                  mcList[key] &&
                  mcList[key].some(
                    (item) =>
                      row >= item.mc.r &&
                      row < item.mc.r + item.mc.rs &&
                      column >= item.mc.c &&
                      column < item.mc.c + item.mc.cs
                  )
                ) {
                  if (row === mcList[key][0].mc.r && column === mcList[key][0].mc.c) {
                    //整列批注
                    ps = {
                      left: null, //批注框左边距
                      top: null, //批注框上边距
                      width: null, //批注框宽度
                      height: null, //批注框高度
                      value: ruleItem[0].tssm, //批准内容
                      isshow: false, //批注框为显示状态
                    }
                  }
                } else {
                  //整列批注
                  ps = {
                    left: null, //批注框左边距
                    top: null, //批注框上边距
                    width: null, //批注框宽度
                    height: null, //批注框高度
                    value: ruleItem[0].tssm, //批准内容
                    isshow: false, //批注框为显示状态
                  }
                }
              }
              // 验证公式
              if (ruleItem[0].yzgs) {
                let str = ruleItem[0].yzgs
                let strList = str ? str.indexOf('n(') > -1 ? str
                  .replace(/(n\()/g, '')
                  .replace(/\)/g, '').trim()
                  .split(',') : str.indexOf('s(') > -1 ? [str] : [] : []
                let status = []
                let value = list[key].value - 0
                strList.map((item) => {
                  if (item.indexOf('gt') > -1) {
                    status.push(value > parseFloat(item.replace(/\-gt/g, '')))
                  } else if (item.indexOf('lt') > -1) {
                    status.push(value < parseFloat(item.replace(/\-lt/g, '')))
                  } else if (item.indexOf('ge') > -1) {
                    status.push(value >= parseFloat(item.replace(/\-ge/g, '')))
                  } else if (item.indexOf('le') > -1) {
                    status.push(value <= parseFloat(item.replace(/\-le/g, '')))
                  } else if (item.indexOf('eq') > -1) {
                    status.push(value == parseFloat(item.replace(/\-eq/g, '')))
                  } else if (item.indexOf('ne') > -1) {
                    status.push(value != parseFloat(item.replace(/\-ne/g, '')))
                  } else if (item.indexOf('s(') > -1) {
                    if (item.indexOf(value) > -1) {
                      status.push(true)
                    }
                  } else {
                    status.push(true)
                  }
                })
                if (status.some((item) => item === true)) {
                  luckysheet.setCellFormat(row, column, 'bg', '#FF0000')
                  luckysheet.setCellFormat(row, column, 'fc', '#ffffff')
                } else {
                  luckysheet.setCellFormat(row, column, 'bg', '#ffffff')
                  luckysheet.setCellFormat(row, column, 'fc', '#000000')
                }
              }
            }
          }
          // 单元格值类型设置，如科学计数法，自动获取配置过的字段，自动读取初始化数据小数位数
          if (qyItem.sjlx && qyItem.sjlx.indexOf(key) >= -1) {
            let sjlx = JSON.parse(qyItem.sjlx)
            sjlx.map(sjItem => {
              if (sjItem.value.some(sjkey => sjkey === key) && sjItem.key === '1') {
                let length = list[key] && list[key].value && list[key].value.indexOf('.') > -1 ? list[key].value.split('.')[1].length : 0;
                let fa = '0.';
                for (let index = 0; index < length; index++) {
                  fa = fa + '0'
                }
                luckysheet.setCellFormat(row, column, 'ct', {
                  "fa": length === 0 ? '@' : fa,
                  "t": length === 0 ? "s" : "n"
                })
              }
            })
          }
          if (ps.value) {
            luckysheet.setCellFormat(row, column, 'ps', ps)
          }
          let vm = {}
          if (!noRenderCol.some((item) => item.toUpperCase() === key)) {
            vm = {
              v: (list[key] && list[key].value) || '',
              m: (list[key] && list[key].value) || '',
            }
            // 带公式不渲染，自动计算
            if (!this.calcChain.some((el) => el.r == row && el.c == column)) {
              window.luckysheet.setCellValue(
                row,
                column,
                {
                  ...vm,
                },
                {
                  isRefresh: i === list.length - 1,
                }
              )

            }
          }
        })
        // if (this.type === 'render') {
        //   setTimeout(() => {
        //     luckysheet.refreshFormula()
        //   }, 200)
        // }
      }
    },
    // 获取数据集配置列表
    getDatasetDataList(record, status) {
      queryDatasetDataList({ bbdm: (record && record.bbdm) || this.exportJson.bbdm }).then((res) => {
        if (res.code === 200) {
          let range = res.result.records || []
          this.sjjpzList = range
          if (this.type === 'target' && range.length > 0 && status) {
            const rangeList = range.map((item) => {
              return JSON.parse(item.xzqy)
            })
            setTimeout(() => {
              this.drawRange(rangeList)
            }, 500)
          }
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
    //数据集配置开始修改
    editSjjpz(record) {
      const data = JSON.parse(JSON.stringify(record))
      this.sjlxList = record.sjlx ? JSON.parse(record.sjlx) : []
      let formData = {
        sjtype: '',
        zdtype: [],
        xzqy: record.xzqy,
        xzmc: record.xzmc,
        tableName: record.sqlval ? record.sqlval.split('FROM')[1].trim() : '',
        columns: record.sqlval ? record.sqlval.replace('SELECT', '').trim().split('FROM')[0].trim().split(',') : [],
        sqlval: record.sqlval,
        hbcolumns: record.hbcolumns ? record.hbcolumns.indexOf(',') > -1 ? record.hbcolumns.split(',') : [record.hbcolumns] : [],
        noRenderCol: record.noRenderCol ? record.noRenderCol.indexOf(',') > -1 ? record.noRenderCol.split(',') : [record.noRenderCol] : [],
        sqlsort:record.sqlOrder?record.sqlOrder.split(' ')[0].indexOf(',')?record.sqlOrder.split(' ')[0].split(','):record.sqlOrder.split(' ')[0]:[],
        sort:record.sqlOrder?record.sqlOrder.split(' ')[1]:'',
      }
      this.queryAllColumns(formData.tableName, true)
      this.sjjpzItem = { ...data, ...formData }
      this.formData = formData
      this.dataSysStatus = false
      const range = JSON.parse(record.xzqy)
      this.dataSysRange = range
      this.clearRange([range])
      luckysheet.setRangeShow(range, {
        show: true,
        order: this.historyRangeInfo.info.order || '0',
      })

    },
    // 数据集配置删除
    deleteSjjpz(record) {
      deleteDatasetData({ id: record.id }).then((res) => {
        if (res.code === 200) {
          if (this.sjjpzItem && this.sjjpzItem.id === record.id) {
            this.clearDataRange()
          } else {
            this.clearRange([JSON.parse(record.xzqy)])
          }
          this.$message.success('删除成功')
          this.getDatasetDataList(record, false)
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
    // 取消修改
    clearDataRange(status) {
      if (status) {
        this.drawRange([JSON.parse(this.sjjpzItem.xzqy)])
      }
      this.sjjpzItem = {}
      this.formData = {}
      this.dataSysStatus = false
      this.dataSysRange = []
      this.$refs.formData.resetFields()
    },
    // 数据集保存
    saveDataRange() {
      // console.log(this.formData);console.log(this.$refs.formData);console.log(this.formData.xzmc)
      // this.$refs.formData.validate((valid) => {
      //   if (valid) {
      const xzqy = JSON.stringify(this.dataSysRange)
      let newFormData = {
        xzqy,
        xzmc: this.formData.xzmc,
        sqlval: this.formData.sqlval,
        hbcolumns: this.formData.hbcolumns.join(','),
        noRenderCol: this.formData.noRenderCol?`${this.formData.noRenderCol.join(',')}` : '',
        sjlx: this.sjlxList.length > 0 && JSON.stringify(this.sjlxList) || '',
        sqlOrder: this.formData.sqlsort ? `${this.formData.sqlsort.join(',')} ${this.formData.sort}` : ''
      }
      if (this.sjjpzItem && this.sjjpzItem.id) {
        editDataset({ ...this.sjjpzItem, ...newFormData }).then((res) => {
          if (res.code === 200) {
            this.sjlxList = []
            this.$message.success('修改成功!')
            this.clearDataRange()
            this.drawRange([JSON.parse(xzqy)])
            this.getDatasetDataList({ bbdm: this.exportJson.bbdm }, false)
          } else {
            this.$message.warning('服务器出错!')
          }
        })
      } else {
        const data = { bbdm: this.exportJson.bbdm, mbdm: this.exportJson.mbbm }
        addDataset({ ...newFormData, ...data }).then((res) => {
          if (res.code === 200) {
            this.sjlxList = []
            this.$message.success('新建成功!')
            this.clearDataRange()
            this.drawRange([JSON.parse(xzqy)])
            this.dataSysRange = {}
            this.getDatasetDataList({ bbdm: this.exportJson.bbdm }, false)
          } else {
            this.$message.warning('服务器出错!')
          }
        })
      }
      // } else {
      //   return false
      // }
      // })
    },
  }
}